package com.app.system.utils.mysql;

import java.io.*;

/**
 * Created by wcf-pc on 2019/1/26.
 */
@SuppressWarnings("all")
public class MySqlBackUtils {

    /**
     * 备份数据库
     *
     * @param ip           数据库ip地址
     * @param port         端口
     * @param userName     用户名
     * @param password     密码
     * @param savePath     保存路径
     * @param fileName     文件名
     * @param dataBaseName 库名
     * @return
     */
    public static boolean dbBackup(String ip, int port, String userName, String password, String savePath, String fileName, String dataBaseName) {
        File saveFile = new File(savePath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
            Process process = Runtime.getRuntime().exec(" mysqldump -h" + ip + " -u" + userName + " -p" + password + " -R -c --set-charset=UTF8 " + dataBaseName);
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            if (process.waitFor() == 0) {//0 表示线程正常终止。
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}
